package com.tdam2014.grupo3.db;

import java.util.ArrayList;
import java.util.Date;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.tdam2014.grupo3.entities.Comment;

public class CommentDatabaseHelper extends DatabaseHelper {

	public CommentDatabaseHelper(Context context) {
		super(context);
	}
	
	public ArrayList<Comment> getCommentList(String photoID) {
		SQLiteDatabase db = this.getReadableDatabase();
		
		String query = "SELECT * FROM " + tblComment + " WHERE " + colCommentPhotoID + "=? ORDER BY " + colCommentDateCreated + " ASC";
		Cursor cursor = db.rawQuery(query, new String [] {photoID});
		
		Comment comment;
		ArrayList<Comment> comments = new ArrayList<Comment>();
		while (cursor.moveToNext()) {
			comment = new Comment();
			comment.setId(cursor.getString(cursor.getColumnIndex(colCommentID)));
			comment.setAuthorName(cursor.getString(cursor.getColumnIndex(colCommentAuthorname)));
			comment.setDateCreated(new Date(cursor.getLong(cursor.getColumnIndex(colCommentDateCreated))));
			comment.setText(cursor.getString(cursor.getColumnIndex(colCommentText)));
			
			comments.add(comment);
		}
		
		return comments;
	}
	
	public void addComments(ArrayList<Comment> comments, String photoID) {
		SQLiteDatabase db = this.getWritableDatabase();
		db.beginTransaction();
		
		ContentValues cv = new ContentValues();
		for(Comment comment : comments) {
			cv.put(colCommentPhotoID, photoID);
			cv.put(colCommentAuthorname, comment.getAuthorName());
			cv.put(colCommentDateCreated, comment.getDateCreated().getTime());
			cv.put(colCommentText, comment.getText());
			
			if(existComment(comment.getId())) {
				db.update(tblComment, cv, colCommentID + "=?", new String[] {comment.getId()});
			} else {
				cv.put(colCommentID, comment.getId());
				db.insert(tblComment, null, cv);
			}
		}
		
		db.setTransactionSuccessful();
		db.endTransaction();
		db.close();
	}
	
	private boolean existComment(String id) {
		SQLiteDatabase db = this.getReadableDatabase();
		Cursor cursor = db.query(tblComment, null, colCommentID + "=?", new String[] {id}, null, null, null);
		return cursor.moveToFirst();
	}
}
